package com.sa.app.utilities;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.widget.Toast;

import com.sa.app.R;
import com.sa.app.activities.ItemActivity;
import com.sa.app.activities.MainActivity;
import com.sa.app.activities.ServiceActivity;

public class AsynchronousInsertUse extends AsyncTask<String, Float, Integer> {

	private final Integer TIME_TO_COMPLETED = 5;

	private ProgressDialog progressDialog;
	private Context cont;
	private Activity ma;
	private Location loc;
	private MyApplication mApp;
	private Boolean error = false;
	private String NFCID;
	private Integer type;
	private String[] extras;
	private String url;

	public AsynchronousInsertUse(Activity ma, Context c, Application app,
			String NFCID, Integer type, String url, String... extras) {
		this.cont = c;
		this.mApp = (MyApplication) app;
		this.ma = ma;
		progressDialog = new ProgressDialog(c);
		progressDialog.setMessage(ma.getString(R.string.find_location));
		this.NFCID = NFCID;
		this.type = type;
		this.extras = extras;
		this.url = url;

	}

	protected void onPreExecute() {

	}

	protected Integer doInBackground(String... urls) {

		Integer res = 1;
		loc = mApp.getLocation();

		if (loc == null | (loc.getAccuracy() >= MyApplication.MIN_GPS_ACCURACY)) {

			progressDialog.show();
			int i = 0;

			while (i < TIME_TO_COMPLETED
					&& (loc == null | loc.getAccuracy() >= MyApplication.MIN_GPS_ACCURACY)) {

				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				i++;
				loc = mApp.getLocation();

			}
		}

		if (loc == null | (loc.getAccuracy() >= MyApplication.MIN_GPS_ACCURACY)) {// &&
			error = true;
		}

		return res;
	}

	protected void onProgressUpdate(Float... valores) {

	}

	protected void onPostExecute(Integer bytes) {

		if (progressDialog.isShowing()) {
			progressDialog.dismiss();
		}

		if (!error) {
			List<String> use = new ArrayList<String>();
			// NFCID, latitude, longitude, type
			Integer latitude = (int) (loc.getLatitude() * 1E6);
			Integer longitude = (int) (loc.getLongitude() * 1E6);
			Integer accuracy = (int) (loc.getAccuracy());

			List<String> r = mApp.getDataBase().getRegionFor(latitude,
					longitude, accuracy);

			use.add(NFCID);
			use.add(r.get(1));
			use.add(r.get(2));
			use.add(String.valueOf(type));

			// if es tagueo y no hay region existente con esas coordenadas,
			// crear region
			if (type.equals(MyApplication.TAGGED)
					&& mApp.getDataBase()
					.selectRegion(Integer.valueOf(r.get(1)),
							Integer.valueOf(r.get(2))).isEmpty()) {
				mApp.getDataBase().insertRegion(r.get(0),
						Integer.valueOf(r.get(1)), Integer.valueOf(r.get(2)),
						Integer.valueOf(r.get(3)));
			}
			if (!type.equals(MyApplication.TAGGED)) {
				use.set(1, null);
				use.set(2, null);
			}

			mApp.getDataBase().insertUse(use);

			// Actualiza la posicion del Item cuando se taguea
			if (type.equals(MyApplication.TAGGED)) {

				List<String> region = mApp.getDataBase().getItemLastRegion(
						NFCID);
				List<List<String>> lAux = mApp.getDataBase().selectItemByNFCID(
						NFCID);
				lAux.get(0).set(7, r.get(1));
				lAux.get(0).set(8, r.get(2));
				mApp.getDataBase().insertItem(lAux.get(0));

				// TODO meto aqui la consulta por no modificar metodos que ya
				// estan en la documentación. Nombre metodo: isErasable()
				String sql = "SELECT * FROM regions, items WHERE regionLatitude=latitude AND regionLongitude=longitude AND regionLatitude="
						+ region.get(1)
						+ " AND regionLongitude="
						+ region.get(2);
				if (mApp.getDataBase().query(sql).isEmpty()) {
					// TODO meto aqui la consulta por no modificar metodos que
					// ya estan en la documentación. Nombre metodo:
					// deleteRegion()

					String q = "DELETE FROM regions WHERE latitude="
							+ region.get(1) + " AND longitude=" + region.get(2);
					mApp.getDataBase().execSQL(q);

				}

			}

			Intent intent = null;
			if (ma instanceof MainActivity) {
				intent = new Intent(cont, ItemActivity.class);
			} else if (ma instanceof ItemActivity) {
				intent = new Intent(cont, ServiceActivity.class);
				String[] Aurl = new String[1];
				Aurl[0] = url;
				intent.putExtra("url", Aurl);
			}
			String array[] = new String[extras.length + 1];
			array[0] = NFCID;
			// Esto hace que esta clase sea mas general y se pueda usar en mas
			// casos, sobre todo sirve para cuando queremos ir desde la lista de
			// servicios virtuales/reales a la webactivity podemos llevarnos en
			// los extrar la informacion que el servicio requiera alias, gps,
			// etc..
			for (int i = 0; i < extras.length; i++) {
				array[i + 1] = extras[i];
			}
			intent.putExtra("item", array);

			intent.setAction("ItemsFragment");

			ma.startActivity(intent);

		} else {
			Toast t = Toast.makeText(
					cont,
					ma.getString(R.string.location_error) + "\n"
							+ ma.getString(R.string.sorry), Toast.LENGTH_LONG);
			t.show();
		}

	}

}
